package org.funtester.performance.books.chapter01.section4;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 阻塞队列添加任务示例
 */
public class BlockAddTask {

    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2, 10L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(2));// 创建线程池,核心线程数1,最大线程数2,线程空闲时间10秒,任务队列为链表阻塞队列
        executor.prestartCoreThread();// 预启动核心线程
        for (int i = 0; i < 4; i++) {
            int sequence = i;// 任务序号,用于标识任务,由于lambda表达式中的变量必须是final或者等效的,所以这里使用局部变量
            Runnable runnable = () -> {
                try {
                    Thread.sleep(1000);// 模拟任务执行,睡眠1秒,避免任务过快执行完毕
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + "  " + System.currentTimeMillis() + "  任务" + sequence + "执行完成");// 打印任务执行完成信息
            };
            executor.getQueue().offer(runnable, 10, TimeUnit.SECONDS);// 将任务放入队列
            System.out.println(Thread.currentThread().getName() + "  " + System.currentTimeMillis() + "  任务" + sequence + "提交成功");// 打印任务提交成功信息
        }
        executor.shutdown();// 关闭线程池,不再接受新任务,但会执行完队列中的任务,并不会立即关闭
    }

}
